package com.company.huisuo.biz.fragment

import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.company.huisuo.R
import com.company.huisuo.base.BaseFragment
import com.company.huisuo.biz.adapter.KRoomDanceAdapter
import com.company.huisuo.biz.bean.MerchantDanceBean
import com.company.huisuo.databinding.FragmentKroomDanceBinding
import com.company.huisuo.ext.toast
import com.company.huisuo.repository.MerchantDanceRepository
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

/**
 * K房团舞页面
 */
class KRoomDanceFragment : BaseFragment<FragmentKroomDanceBinding>() {

    private val mDanceAdapter by lazy {
        KRoomDanceAdapter()
    }
    
    private val mMerchantDanceRepository by lazy {
        MerchantDanceRepository()
    }

    companion object {
        fun newInstance(): KRoomDanceFragment {
            return KRoomDanceFragment()
        }
    }

    override fun initView() {
        mBinding?.rcvDanceList?.apply {
            layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false)
            adapter = mDanceAdapter
        }
    }

    override fun initData() {
        loadMerchantDanceList()
    }
    
    /**
     * 加载商家舞蹈列表
     */
    private fun loadMerchantDanceList() {
        lifecycleScope.launch {
            try {
                val result = mMerchantDanceRepository.getMerchantDanceList()
                result.onSuccess { danceList ->
                    mDanceAdapter.submitList(danceList)
                }.onFailure { error ->
                    error.message?.toast()
                    // 如果API调用失败，使用模拟数据
                    mDanceAdapter.submitList(mockDanceData())
                }
            } catch (e: Exception) {
                e.message?.toast()
                // 如果发生异常，使用模拟数据
                mDanceAdapter.submitList(mockDanceData())
            }
        }
    }
    
    /**
     * 模拟团舞数据
     */
    private fun mockDanceData(): List<MerchantDanceBean> {
        val list = ArrayList<MerchantDanceBean>()
        list.add(MerchantDanceBean(1L, "dance001", "劲爆街舞", 180, "https://picsum.photos/seed/dance001/400/400.jpg", 100.0))
        list.add(MerchantDanceBean(2L, "dance002", "劲爆街舞", 180, "https://picsum.photos/seed/dance002/400/400.jpg", 100.0))
        list.add(MerchantDanceBean(3L, "dance003", "劲爆街舞", 180, "https://picsum.photos/seed/dance003/400/400.jpg", 100.0))
        list.add(MerchantDanceBean(4L, "dance004", "劲爆街舞", 180, "https://picsum.photos/seed/dance004/400/400.jpg", 100.0))
        list.add(MerchantDanceBean(5L, "dance005", "劲爆街舞", 180, "https://picsum.photos/seed/dance005/400/400.jpg", 100.0))
        return list
    }
}